import 'package:common_utils/common_utils.dart';
import 'package:drm/base/page.dart';
import 'package:drm/base/tj_date_entity.dart';
import 'package:drm/base/user.dart';
import 'package:drm/char_view/one_page.dart';
import 'package:drm/char_view/three_page.dart';
import 'package:drm/char_view/tow_page.dart';
import 'package:drm/char_view/two_entity.dart';
import 'package:drm/dialog/date_time_dialog.dart';
import 'package:drm/http/date_result.dart';
import 'package:drm/util/SpUtils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:drm/base/chart_view_flag.dart';

import 'package:drm/util/utils.dart';
import 'package:drm/char_view/four_page.dart';

import 'bloc.dart';

class ChartPage extends StatefulWidget {
  String title;
  ChartViewFlag flag;
  Map<String, dynamic> params;

  ChartPage({Key key, this.title, this.flag}) : super(key: key);

  @override
  _ChartPageState createState() => _ChartPageState();
}

class _ChartPageState extends PageState<ChartPage> {
  String ksrq = DateUtil.getDateStrByDateTime(DateTime.now(),
          format: DateFormat.YEAR_MONTH) +
      '-01';
  String jsrq = MyUtils.getNowMonthLastDay();
  String nf = '${DateTime.now().year}';
  String subTitle;
  User user;
  ChartPageBloc _chartPageBloc = ChartPageBloc();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    user = SpUtils.getLocalUser();
    getData(widget.flag);
  }

  @override
  addBlocToBlocList() {
    // TODO: implement addBlocToBlocList
    getBlocs().add(_chartPageBloc);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget mainView(BuildContext context) {
    return BlocBuilder(
        bloc: _chartPageBloc,
        builder: (context, chartState) {
          getStateDo(context, chartState);

          return Scaffold(
              appBar: AppBar(
                title: Text(widget.title),
                actions: <Widget>[
                  IconButton(
                      icon: Icon(Icons.search),
                      onPressed: () {
                        searchDialog(context);
                      }),
                ],
              ),
              body: Container(
                margin: EdgeInsets.all(10),
                child: Center(
                    child: ListView(
                  children: <Widget>[
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Text(
                          widget.title,
                          style: TextStyle(
                              fontSize: 20, fontWeight: FontWeight.bold),
                        ),
                        Text(subTitle),
                        Padding(padding: EdgeInsets.only(left: 5,right: 5),
                        child:  chartView(context, chartState),),


//                      backView(context, chartState),
                      ],
                    ),
                  ],
                )),
              ));
        });
  }

  // 根据不同的index ，初始化不同的日期对话框；
  searchDialog(BuildContext context) {
    switch (widget.flag) {
      case ChartViewFlag.QYXSETJ:
      case ChartViewFlag.XJDHTHTJ:
      case ChartViewFlag.SYDLSXSETJ:
      case ChartViewFlag.XJDLSDHTJ:
      case ChartViewFlag.DLS_XS_TH_TJ:
        DateTimeDialog.showPickerDateRange(context, ksrq, jsrq)
            .then((SearchDate datetime) {
          ksrq = datetime.ksrq;
          jsrq = datetime.jsrq;
          print('ksrq = $ksrq ,jsrq= $jsrq');
          getData(widget.flag);
        });

        break;
      case ChartViewFlag.XJDLSYDHETJ:
      case ChartViewFlag.DLS_XSE_TJ:
        DateTimeDialog.showYearPicker(context, nf, (String select) {
          nf = select;
          getData(widget.flag);
        });

//        DateTimeDialog.showPickerYearDate(context, nf, (String select) {
//          nf = select;
//          getData(widget.flag);
//        });
        break;
    }
  }

  // 根据不同的state 返回不同的图表子页面；
  Widget chartView(BuildContext context, ChartPageState state) {
    return BlocBuilder(
        bloc: _chartPageBloc,
        builder: (context, chartState) {
          if (state is PageGetDateEventState) {
            hideLoading();
            DateResult<List<TjDateEntity>> result = state.datas;
            if (state.unit == 'DLS_XS_TH_TJ') {
              return iniPage<TjDateEntity>(
                  result.data,
                  FourPage(
                    data: result.data,
                  ),
                  oneHeight: 130);
            } else {
              return iniPage<TjDateEntity>(
                  result.data,
                  OnePage(
                    data: result.data,
                    unit: state.unit,
                  ));
            }
          } else if (state is PageGetTwoDateEventState) {
            hideLoading();
            DateResult<List<TwoEntity>> result = state.datas;
            return iniPage<TwoEntity>(result.data, TwoPage(data: result.data),
                oneHeight: 130);
          } else if (state is PageGetThreeDateEventState) {
            hideLoading();
            DateResult<List<TjDateEntity>> result = state.datas;
            return iniPage<TjDateEntity>(
                result.data, ThreePage(data: result.data));
          } else {
            return Container();
          }
        });
  }

  // 子页面初始化
  Widget iniPage<T>(List<T> data, Widget page, {double oneHeight = 0}) {
    if (data == null || data.length == 0) {
      return Container();
    } else {
      if (oneHeight != 0) {
      } else {
        if (data.length > 3) {
          oneHeight = 50;
        } else {
          oneHeight = 80;
        }
      }

      print('oneHegiht=$oneHeight');
      double countHeight = oneHeight * data.length;
      return SizedBox(
        height: countHeight,
        child: page,
      );
    }
  }

  ///
  /// 获取网络数据；
  ///
  ///
  void getData(ChartViewFlag flag) {
    showLoading();
    Map<String, String> params;
    switch (flag) {
      case ChartViewFlag.QYXSETJ:
        params = {
          'Type': 'QYXSETJ',
          'DLSId': '${user.dlsId}',
          'DLSTopId': '${user.dlsTopId}',
          'XSRQ': '$ksrq',
          'XSRQ1': '$jsrq',
        };
        subTitle = '$ksrq 至 $jsrq';
        _chartPageBloc.dispatch(PageGetDateEvent(params, unit: '元'));
        break;
      case ChartViewFlag.XJDLSDHTJ:
        //  Type=XJDLSDHTJ//下级代理商订货数量统计（需要传递：XSRQ，XSRQ1，DLSId）
        params = {
          'Type': 'XJDLSDHTJ',
          'XSRQ': '$ksrq',
          'XSRQ1': '$jsrq',
          'DLSId': '${user.dlsId}',
          'DLSTopId': '${user.dlsTopId}',
        };
        subTitle = '$ksrq 至 $jsrq';
        _chartPageBloc.dispatch(PageGetDateEvent(params));
        break;
      case ChartViewFlag.SYDLSXSETJ:
        params = {
          'Type': 'SYDLSXSETJ',
          'XSRQ': '$ksrq',
          'XSRQ1': '$jsrq',
          'DLSId': '${user.dlsId}',
          'DLSTopId': '${user.dlsTopId}',
        };
        subTitle = '$ksrq 至 $jsrq';
        _chartPageBloc.dispatch(PageGetDateEvent(params, unit: '元'));
        break;
      case ChartViewFlag.XJDLSYDHETJ:
        params = {
          'Type': 'XJDLSYDHETJ',
          'NF': nf,
          'DLSId': '${user.dlsId}',
          'DLSTopId': '${user.dlsTopId}'
        };
        subTitle = '$nf年';
        _chartPageBloc.dispatch(PageGetDateEvent(params, unit: '元'));
        break;
      case ChartViewFlag.XJDHTHTJ:
        params = {
          'Type': 'XJDHTHTJ',
          'DLSId': '${user.dlsId}',
          'XSRQ': '$ksrq',
          'XSRQ1': '$jsrq',
          'DLSTopId': '${user.dlsTopId}',
        };
        subTitle = '$ksrq 至 $jsrq';
        _chartPageBloc.dispatch(PageGetTwoDateEvent(params));
        break;
      case ChartViewFlag.DLS_XS_TH_TJ:
        params = {
          'Type': 'DLS_XS_TH_TJ',
          'XSRQ': '$ksrq',
          'XSRQ1': '$jsrq',
          'DLSId': '${user.dlsId}',
          'DLSTopId': '${user.dlsTopId}',
        };
        subTitle = '$ksrq 至 $jsrq';
        _chartPageBloc.dispatch(PageGetDateEvent(params, unit: 'DLS_XS_TH_TJ'));
        break;
      case ChartViewFlag.DLS_XSE_TJ:
        params = {
          'Type': 'DLS_XSE_TJ',
          'NF': nf,
          'DLSId': '${user.dlsId}',
          'DLSTopId': '${user.dlsTopId}'
        };
        subTitle = '$nf年';
        _chartPageBloc.dispatch(PageGetDateEvent(params, unit: '元'));
        break;
    }
  }

  Widget backView(BuildContext context, ChartPageState state) {
//    return BlocListener(
//      bloc: _chartPageBloc,
//      listener: (context,state) {
//        if ( state is CloseState) {
//          Navigator.of(context).pop();
//        }
//      }
//    );
  }

  getStateDo(BuildContext context, ChartPageState state) {}
}
